﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Prototype
{
    public partial class new_item : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        private OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings["AutoFixConnectionString"].ToString());
  
        protected void btnAddArticle_Click(object sender, EventArgs e)
        {
            string articleName = this.txtArticleName.Text.Trim();
            string stepContent = this.txtStep.Text.Trim();
            string stepTitle = this.txtStepTitle.Text.Trim();

            string fileName = string.Empty;
            string file = string.Empty;

            if (this.fleUploadImage.HasFile)
            {
                if (this.fleUploadImage.PostedFile.ContentType == "image/jpeg")
                {
                    Guid guid = Guid.NewGuid();
                    fileName = "images/" + guid + ".jpg";
                    file = Request.MapPath("images/") + guid + ".jpg";
                    fleUploadImage.SaveAs(file);
                }
                else
                {
                    this.lblMessage.Text = "Invalid image file. Only jpg format is allowed";
                    this.lblMessage.Attributes.Add("class", "error-msg");
                }
            }
            InsertArticleToDatabase(articleName, stepTitle, stepContent, fileName);


        }
        /// <summary>
        /// Inserts an article to the database
        /// </summary>
        /// <param name="articleName">article name</param>
        /// <param name="stepTitle">step title</param>
        /// <param name="stepContent">step content</param>
        /// <param name="articleImagePath">article image path</param>
        private void InsertArticleToDatabase(string articleName, string stepTitle, string stepContent, string articleImagePath)
        {
            string articleImage = (articleImagePath == "") ? "images/imgNoImage.jpg" : articleImagePath;
            int numberOfRowsAffected = 0;
            string sql = @"INSERT INTO Article (ArticleName, ArticleImageUrl, UserID, IsPublished, IsActive)
                            VALUES(@f1, @f2, @f3, @f4, @f5)";
            OleDbCommand cmdInsertArticle = new OleDbCommand(sql, connection);
            cmdInsertArticle.CommandType = System.Data.CommandType.Text;
            cmdInsertArticle.Parameters.AddWithValue("@f1", articleName);
            cmdInsertArticle.Parameters.AddWithValue("@f2", articleImage);
            cmdInsertArticle.Parameters.AddWithValue("@f3", 2);
            cmdInsertArticle.Parameters.AddWithValue("@f4", true);
            cmdInsertArticle.Parameters.AddWithValue("@f5", true);
            if (connection.State == System.Data.ConnectionState.Closed)
            {
                connection.Open();
            }
            numberOfRowsAffected = cmdInsertArticle.ExecuteNonQuery();


            if (numberOfRowsAffected > 0)
            {

                string stepFilePath = AddStepContentInDirectory(stepContent);
                int articleID = GetLastArticleID();
                if (articleID > 0)
                {
                    int numberOfRowsAffectedInSteps = 0;
                    string sqlStep = @"INSERT INTO Step (StepName, StepURL, ArticleID, IsActive)
                            VALUES(@f1, @f2, @f3, @f4)";
                    OleDbCommand cmdInsertStep = new OleDbCommand(sqlStep, connection);
                    cmdInsertStep.CommandType = System.Data.CommandType.Text;
                    cmdInsertStep.Parameters.AddWithValue("@f1", stepTitle);
                    cmdInsertStep.Parameters.AddWithValue("@f2", stepFilePath);
                    cmdInsertStep.Parameters.AddWithValue("@f3", articleID);
                    cmdInsertStep.Parameters.AddWithValue("@f4", true);
                    cmdInsertStep.Parameters.AddWithValue("@f5", true);
                    if (connection.State == System.Data.ConnectionState.Closed)
                    {
                        connection.Open();
                    }
                    numberOfRowsAffectedInSteps = cmdInsertStep.ExecuteNonQuery();

                    if (numberOfRowsAffectedInSteps > 0)
                    {
                        lblMessage.Text = "The article has been added successfully";
                        lblMessage.Attributes.Add("class", "success-msg");
                    }
                    else
                    {

                        lblMessage.Text = "Sorry, we weren't able to add a step to this article";
                        lblMessage.Attributes.Add("class", "error-msg");
                    }


                }
                else
                {
                    lblMessage.Text = "Sorry, we weren't able to add the article";
                    lblMessage.Attributes.Add("class", "error-msg");
                }
            }
        }
        /// <summary>
        /// Gets the last article ID added to the table
        /// </summary>
        /// <returns>article ID</returns>
        private int GetLastArticleID()
        {
            int articleID = 0;
            string sqlLast = @"SELECT TOP 1 ArticleID FROM Article
                                ORDER BY ArticleID DESC;";
            OleDbCommand cmdSelectLastArticle = new OleDbCommand(sqlLast, connection);
            OleDbDataReader dataReader = null;
            dataReader = cmdSelectLastArticle.ExecuteReader();
            if (connection.State == System.Data.ConnectionState.Closed)
            {
                connection.Open();
            }
            dataReader.Read();

            if (dataReader.HasRows)
            {
                articleID = Convert.ToInt32(dataReader.GetValue(0).ToString());
            }
            return articleID;
        }
        /// <summary>
        /// Adds the step content data to a text file
        /// </summary>
        /// <param name="stepContent">step content</param>
        /// <returns>the file path to be added to the step table</returns>
        private string AddStepContentInDirectory(string stepContent)
        {
            string pathToFile = string.Empty;
            string completeDirectoryPath = string.Empty;
            int articleID = GetLastArticleID();
            if (articleID > 0)
            {
                pathToFile = "/steps/" + articleID;
                completeDirectoryPath = Server.MapPath(pathToFile);
                if (!Directory.Exists(pathToFile))
                {
                    Directory.CreateDirectory(completeDirectoryPath);
                    completeDirectoryPath = Path.Combine(completeDirectoryPath, articleID + ".txt");
                    if (!File.Exists(completeDirectoryPath))
                    {
                        using (FileStream fileStream = File.Create(completeDirectoryPath))
                        {
                            fileStream.Close();
                        }
                        using (StreamWriter stepContentWriter = new StreamWriter(completeDirectoryPath, true))
                        {
                            stepContentWriter.WriteLine(stepContent);
                            pathToFile = pathToFile + "/" + articleID + ".txt";
                        }
                        
                    }
                }
            }


            return pathToFile;
        }
    }
}